import Vue from 'vue'
import VueRouter from 'vue-router'
import UploadPage from '../views/UploadPage.vue'
import PatientList from '../views/PatientList.vue'
import ViewerPage from '../views/ViewerPage.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/patients'
  },
  {
    path: '/upload',
    name: 'Upload',
    component: UploadPage
  },
  {
    path: '/patients',
    name: 'PatientList',
    component: PatientList
  },
  {
    path: '/viewer/:patientId/:studyId',
    name: 'Viewer',
    component: ViewerPage,
    props: route => ({
      patientId: String(route.params.patientId),
      studyId: String(route.params.studyId),
      preloadStrategy: route.query.preload || 'auto'
    }),
    meta: {
      requiresPreload: true,
      preloadTimeout: 30000
    }
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach(async (to, from, next) => {
  if (to.meta.requiresPreload) {
    console.log('路由需要预加载资源:', to.path);
    
    const timeout = to.meta.preloadTimeout || 10000;
    const preloadPromise = new Promise(async (resolve) => {
      try {
        if (to.params.patientId) {
          // 这里可以调用API预加载数据
        }
        resolve();
      } catch (error) {
        console.error('预加载失败:', error);
        resolve();
      }
    });
    
    const timeoutPromise = new Promise(resolve => {
      setTimeout(() => {
        console.warn(`预加载超时 (${timeout}ms)`);
        resolve();
      }, timeout);
    });
    
    await Promise.race([preloadPromise, timeoutPromise]);
  }
  
  next();
});

export default router 